<script setup>
import { shallowRef, onUnmounted } from 'vue'
import vMap from '@/components/mapbox-map.vue'
import MapboxDraw from '@mapbox/mapbox-gl-draw'
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'

const emit = defineEmits(['load'])

const props = defineProps({
  controls: {
    type: Object,
    default: () => ({
      point: true,
      line_string: true,
      polygon: true,
      trash: true,
    }),
  },
})

const drawInstance = shallowRef(null)
const mapInstance = shallowRef(null)

const init = () => {
  const draw = new MapboxDraw({
    displayControlsDefault: false,
    controls: props.controls,
  })
  mapInstance.value.addControl(draw, 'top-right')
  drawInstance.value = draw
  emit('load', draw, mapInstance.value)
}

const load = (_, map) => {
  mapInstance.value = map
  init()
}

onUnmounted(() => {
  if (mapInstance.value) {
    mapInstance.value.removeControl(drawInstance.value)
  }

  if (drawInstance.value) {
    drawInstance.value = null
    mapInstance.value = null
  }
})

defineExpose({
  draw: drawInstance,
  map: mapInstance,
})
</script>

<template>
  <div class="mapbox-gl-draw-container">
    <v-map mapId="mapbox-gl-draw" @after-map-loaded="load" />
    <slot />
  </div>
</template>

<style lang="scss" scoped>
.mapbox-gl-draw-container {
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
